package com.mofee.db;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Mofee.Zhang
 * @date 2018/4/25 9:38
 */
public class DBUtils {
    private static final String URL = "jdbc:mysql://localhost:3306/mofee?characterEncoding=UTF-8";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    static {
        DbUtils.loadDriver("com.mysql.jdbc.Driver");
    }

    private static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void exec(final String sql, final Object... params) {
        QueryRunner runner = new QueryRunner();
        Connection connection = getConnection();
        try {
            if (connection != null) {
                runner.execute(connection, sql, params);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
    }

}
